import { createRouter, createWebHashHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";

import Home from "./views/Home.vue";
import Login from "./views/Login.vue";
import TodoList from "./views/TodoList.vue";
import NewTodo from "./views/NewTodo.vue";

import { useUserStore } from "./store";

const routes = [
  {
    name: "home",
    path: "/",
    component: Home,
    redirect: { name: "todo.list" },
    children: [
      {
        name: "todo.list",
        path: "todos",
        component: TodoList,
      },
      {
        name: "todo.new",
        path: "todo/new",
        component: NewTodo,
      },
      {
        name:'todo.editTodo',
        path:'todo/editTodo/:id',
        component:NewTodo
    }
    ],
  },
  {
    name: "login",
    path: "/login",
    component: Login,
  },
  {
    name: "register",
    path: "/register",
    component: () => import("./views/Register.vue"),
  },
  {
    name: "about",
    path: "/about",
    component: () => import("./views/About.vue"),
  },
] as RouteRecordRaw[];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

// 需要用户登录的路由列表
const requestLogin = ["home"];
// 使用全局前置路由约束用户（权限检查）跳转
router.beforeEach(async (to) => {
  // 验证当前用户是否登录
  const userStore = useUserStore();
  if (
    requestLogin.includes(to.name as string) ||
    (to.name as string).startsWith("todo")
  ) {
    await userStore.getUserInfo();
    if (userStore.user == null) return { name: "login" };
  }
  return true;
});

export default router;
